package cn.com.blueInfo.core.manager;

import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import lombok.Getter;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.security.*;
import java.util.concurrent.TimeUnit;

@Getter
@Component
public class EncryptionKeyManager {

    /** RSA密钥长度，推荐至少2048位 */
    private static final int KEY_SIZE = 2048;
    /** 标记是否处于密钥轮换期 */
    private boolean isKeyRotating = false;

    private boolean isKeyRotating_http = false;

    // 当前使用的密钥对
    /** 对称加密密钥 */
    private Key secretKey;
    /** 非对称加密私钥-加密 */
    private PrivateKey privateKey;
    /** 非对称加密公钥-解密 */
    private PublicKey publicKey;

    // 旧密钥对（用于轮换期间的兼容）
    /** 对称加密密钥 */
    private Key oldSecretKey;
    /** 非对称加密私钥-加密 */
    private PrivateKey oldPrivateKey;
    /** 非对称加密公钥-解密 */
    private PublicKey oldPublicKey;

    // 当前使用的密钥对（前端请求）
    /** 对称加密密钥 */
    private Key secretKey_http;
    /** 非对称加密私钥-加密 */
    private PrivateKey privateKey_http;
    /** 非对称加密公钥-解密 */
    private PublicKey publicKey_http;

    // 旧密钥对（用于轮换期间的兼容）
    /** 对称加密密钥 */
    private Key oldSecretKey_http;
    /** 非对称加密私钥-加密 */
    private PrivateKey oldPrivateKey_http;
    /** 非对称加密公钥-解密 */
    private PublicKey oldPublicKey_http;


    @PostConstruct
    public void init() throws NoSuchAlgorithmException {
        this.secretKey = Keys.secretKeyFor(SignatureAlgorithm.HS256);

        // 生成RSA密钥对
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(KEY_SIZE);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        this.privateKey = keyPair.getPrivate();
        this.publicKey = keyPair.getPublic();



        this.secretKey_http = Keys.secretKeyFor(SignatureAlgorithm.HS256);

        // 生成RSA密钥对
        KeyPairGenerator keyPairGenerator_http = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator_http.initialize(KEY_SIZE);
        KeyPair keyPair_http = keyPairGenerator_http.generateKeyPair();

        this.privateKey_http = keyPair_http.getPrivate();
        this.publicKey_http = keyPair_http.getPublic();
    }

    @Scheduled(fixedRate = 24, timeUnit = TimeUnit.HOURS)
    public synchronized void rotateKeys() throws NoSuchAlgorithmException {
        // 将当前密钥保存为旧密钥
        this.oldSecretKey = this.secretKey;
        this.oldPrivateKey = this.privateKey;
        this.oldPublicKey = this.publicKey;

        // 生成新的密钥对
        generateNewKeys();

        // 标记进入密钥轮换期
        isKeyRotating = true;

        // 60分钟后清除旧密钥，结束轮换期
        new Thread(() -> {
            try {
                Thread.sleep(TimeUnit.HOURS.toMillis(1));
                synchronized (this) {
                    oldSecretKey = null;
                    oldPrivateKey = null;
                    oldPublicKey = null;
                    isKeyRotating = false;
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }).start();
    }

    /**
     * 初始化新密钥
     */
    private void generateNewKeys() throws NoSuchAlgorithmException {
        this.secretKey = Keys.secretKeyFor(SignatureAlgorithm.HS256);

        // 生成RSA密钥对
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(KEY_SIZE);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        this.privateKey = keyPair.getPrivate();
        this.publicKey = keyPair.getPublic();
    }

    @Scheduled(fixedRate = 1, timeUnit = TimeUnit.HOURS)
    public synchronized void rotateKeys_http() throws NoSuchAlgorithmException {
        // 将当前密钥保存为旧密钥
        this.oldSecretKey_http = this.secretKey_http;
        this.oldPrivateKey_http = this.privateKey_http;
        this.oldPublicKey_http = this.publicKey_http;

        // 生成新的密钥对
        generateNewKeys_http();

        // 标记进入密钥轮换期
        isKeyRotating_http = true;

        // 60分钟后清除旧密钥，结束轮换期
        new Thread(() -> {
            try {
                Thread.sleep(TimeUnit.MINUTES.toMillis(1));
                synchronized (this) {
                    oldSecretKey_http = null;
                    oldPrivateKey_http = null;
                    oldPublicKey_http = null;
                    isKeyRotating_http = false;
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }).start();
    }

    /**
     * 初始化新密钥
     */
    private void generateNewKeys_http() throws NoSuchAlgorithmException {
        this.secretKey_http = Keys.secretKeyFor(SignatureAlgorithm.HS256);

        // 生成RSA密钥对
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(KEY_SIZE);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        this.privateKey_http = keyPair.getPrivate();
        this.publicKey_http = keyPair.getPublic();
    }

}
